package com.baitiaojun.security.core.utils;

import cn.hutool.core.map.MapUtil;
import com.baitiaojun.common.constants.Constants;
import com.baitiaojun.common.utils.id.IdUtils;
import com.baitiaojun.common.utils.id.UUID;
import com.baitiaojun.common.utils.string.StringUtils;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import lombok.extern.slf4j.Slf4j;

import javax.servlet.http.HttpServletRequest;
import java.util.Calendar;

/**
 * token处理工具
 */
@Slf4j
public class TokenUtils {

    /**
     * 生成tokne不指定过期时间
     *
     * @param subject
     * @param secret
     * @param refreshExpire
     * @return
     */
    public static String createToken(String subject, String secret, String refreshExpire) {
        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.DAY_OF_WEEK, Integer.parseInt(refreshExpire));
        return Jwts.builder()
                .signWith(SignatureAlgorithm.HS256, secret) //指定算法
                .setClaims(MapUtil.of(Constants.LOGIN_USER_KEY, subject))
                .setExpiration(calendar.getTime()) //指定过期时间
                .compact();
    }


    /**
     * 解析token的payload, 如果解析失败就说明令牌过期
     * @param token
     * @return
     */
    public static Claims parseToken(String token, String secret) {
        try {
            return Jwts.parser().setSigningKey(secret)
                    .parseClaimsJws(token)
                    .getBody();
        } catch (Exception e) {
            log.warn("{}, 令牌解析失败:{}", e.getMessage(), token);
            return null;
        }
    }


    /**
     * 获取有效的token部分
     * @param request
     * @return
     */
    public static String subToken(HttpServletRequest request, String tokenSign) {
        String token = request.getHeader(tokenSign);
        if (StringUtils.isNotEmpty(token) && token.startsWith(Constants.TOKEN_PREFIX)) {
            token = token.replaceFirst(Constants.TOKEN_PREFIX, "").trim();
        }
        return token;
    }

    public static void main(String[] args) {
//        System.out.println(createToken(IdUtils.fastUUID(), "abcdefghijklmnopqrstuvwxyz", "7"));
//        System.out.println(parseToken("eyJhbGciOiJIUzUxMiJ9.eyJzdWJqZWN0IjoiYzM1YmIwZDUtYTVkNS00YTU1LTlkMzctMmZlYzJlN2M2ZGY0In0.Rbx6AIGwL3ZVYyFjlZR6C9khAOR7AtC9_KA5pfk5HWwfKBq1iOoxt7HkqC-W_Hr_XRPCk0GxvoWpnutdh-sM2g").get("subject"));
    }
}
